<template>
  <div class="relative bg-gradient-to-br from-indigo-50 to-purple-50 p-4 lg:p-6 rounded-2xl shadow-lg lg:shadow-2xl ">
    <!-- 动态背景粒子 -->
    <div ref="particlesRef" class="absolute inset-0 z-0"></div>

    <!-- 奖杯装饰元素 -->
    <div class="absolute top-6 right-6 z-10">
      <!-- <Icon name="mdi:trophy" class="text-yellow-400 text-3xl animate-bounce" />
      <Icon name="mdi:trophy" class="text-gray-300 text-3xl -mt-3 animate-bounce" style="animation-delay: 0.3s" />
      <Icon name="mdi:trophy" class="text-amber-700 text-3xl -mt-3 animate-bounce" style="animation-delay: 0.6s" /> -->
    </div>

    <!-- 标题区域 -->
    <div class="relative z-10 flex items-center mb-6">
      <h2
        class="text-xl text-3xl font-display text-transparent bg-clip-text bg-gradient-to-r from-primary to-secondary mr-3">
        {{ title }}
      </h2>
      <span
        class="inline-block px-3 py-1 bg-accent/40 min-w-fit text-accent rounded-full text-sm font-bold animate-pulse">
        {{ updateFrequency }}
      </span>
    </div>

    <!-- 可视化图表 -->
    <div ref="chartEl" class="h-64 lg:h-96 w-full relative z-10 transform transition-all hover:scale-[1.02]"></div>

    <!-- 用户排名卡片 -->
    <div v-if="userRank"
      class="relative mt-4 lg:mt-8 p-3 lg:p-5 bg-gradient-to-r from-purple-500/10 to-blue-500/10 rounded-xl backdrop-blur-sm border border-white/30 shadow-xl overflow-hidden"
      @mouseenter="startFlareAnimation">
      <!-- 动态光效 -->
      <div ref="flareRef" class="absolute inset-0 pointer-events-none"></div>

      <div class="relative z-10">
        <h3 class="font-bold flex items-center gap-2 text-purple-800">
          <!-- <Icon name="mdi:chart-line" class="text-purple-600" /> -->
          艺术家排名追踪
        </h3>
        <div class="mt-3 flex items-center justify-between">
          <div class="flex items-end">
            <span class="text-4xl font-bold text-secondary bg-white/80 px-4 py-2 rounded-lg shadow">
              #{{ userRank.current }}
            </span>
            <div class="ml-4 flex flex-col">
              <span class="text-sm text-gray-600 mb-1">历史最佳</span>
              <span class="text-lg font-bold text-primary">#{{ userRank.best }}</span>
            </div>
          </div>

          <div class="flex items-center px-4 py-2 rounded-full bg-white shadow-md"
            :class="userRank.trend > 0 ? 'text-green-600' : 'text-red-500'">
            <span class="mr-2 font-semibold">{{ Math.abs(userRank.trend) }}位</span>
            <!-- <Icon :name="userRank.trend > 0 ? 'mdi:trending-up' : 'mdi:trending-down'" size="24"
              class="animate-pulse" /> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import * as THREE from 'three'
import { gsap } from 'gsap'

const props = defineProps<{
  title: string
  data: RankingItem[]
  updateFrequency: string
  userRank?: {
    current: number
    trend: number
    best: number
  }
}>()

const chartEl = ref<HTMLElement | null>(null)
const particlesRef = ref<HTMLElement | null>(null)
const flareRef = ref<HTMLElement | null>(null)

// 粒子系统初始化
const initParticles = () => {
  if (!particlesRef.value) return
  const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent)
  if (isMobile || !particlesRef.value) return

  const scene = new THREE.Scene()
  const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  const renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true })

  renderer.setSize(particlesRef.value.clientWidth, particlesRef.value.clientHeight)
  particlesRef.value.appendChild(renderer.domElement)

  camera.position.z = 5

  // 创建粒子
  const particles = []
  const geometry = new THREE.BufferGeometry()
  const material = new THREE.PointsMaterial({
    color: 0x7e5bef,
    size: 0.05,
    transparent: true,
    opacity: 0.7
  })

  for (let i = 0; i < 300; i++) {
    const x = (Math.random() - 0.5) * 10
    const y = (Math.random() - 0.5) * 10
    const z = (Math.random() - 0.5) * 10
    particles.push(x, y, z)
  }

  geometry.setAttribute('position', new THREE.Float32BufferAttribute(particles, 3))
  const particleSystem = new THREE.Points(geometry, material)
  scene.add(particleSystem)

  // 动画
  const animate = () => {
    requestAnimationFrame(animate)

    particleSystem.rotation.x += 0.0005
    particleSystem.rotation.y += 0.001

    const positions = particleSystem.geometry.attributes.position.array
    for (let i = 0; i < positions.length; i += 3) {
      positions[i] += (Math.random() - 0.5) * 0.005
      positions[i + 1] += (Math.random() - 0.5) * 0.005
    }

    particleSystem.geometry.attributes.position.needsUpdate = true
    renderer.render(scene, camera)
  }

  animate()

  // 响应式调整
  const handleResize = () => {
    camera.aspect = particlesRef.value!.clientWidth / particlesRef.value!.clientHeight
    camera.updateProjectionMatrix()
    renderer.setSize(particlesRef.value!.clientWidth, particlesRef.value!.clientHeight)
  }

  window.addEventListener('resize', handleResize)
}

// 光效动画
const startFlareAnimation = () => {
  if (!flareRef.value) return
  if (window.innerWidth < 768) return // 移动端不执行


  const flare = document.createElement('div')
  flare.className = 'absolute w-40 h-40 rounded-full bg-gradient-to-r from-purple-400/30 to-blue-400/30 blur-xl'
  flare.style.top = `${Math.random() * 100}%`
  flare.style.left = `${Math.random() * 100}%`
  flareRef.value.appendChild(flare)

  gsap.fromTo(flare,
    { scale: 0, opacity: 0 },
    {
      scale: 1.5,
      opacity: 0.8,
      duration: 0.8,
      onComplete: () => {
        gsap.to(flare, {
          scale: 2.5,
          opacity: 0,
          duration: 0.5,
          onComplete: () => flare.remove()
        })
      }
    }
  )
}

interface RankingItem {
  name: string
  value: number
  artwork?: string
  change?: number
}

onMounted(() => {
  initParticles()
  if (chartEl.value) renderChart()
})

watch(() => props.data, () => {
  if (chartEl.value) renderChart()
})

const renderChart = () => {
  if (!echarts || !chartEl.value) return

  const chart = echarts.init(chartEl.value)
  // chart.getZr().on('touchstart', (e) => {
  //   chart.dispatchAction({
  //     type: 'showTip',
  //     x: e.offsetX,
  //     y: e.offsetY
  //   })
  // })
  // 生成渐变颜色
  const generateGradient = (index: number) => {
    const colors = [
      ['#FFD166', '#F72585'], // 第一名
      ['#b6b6b6', '#4361ee'], // 第二名
      ['#CD7F32', '#7209b7'], // 第三名
      ['#3A0CA3', '#4CC9F0']  // 其余
    ]

    const colorIndex = index < 3 ? index : 3
    return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
      { offset: 0, color: colors[colorIndex][0] },
      { offset: 1, color: colors[colorIndex][1] }
    ])
  }

  const options = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#3A0CA3',
      borderWidth: 1,
      textStyle: {
        color: '#2b2d42'
      },
      formatter: (params: any) => {
        const data = params[0]
        return `
          <div class="font-bold text-lg text-primary">${data.name}</div>
          <div class="text-gray-600 mb-2">影响力指数: <span class="font-bold">${data.value}</span></div>
          ${data.data.change ? `
            <div class="inline-block px-2 py-1 rounded-full ${data.data.change > 0
              ? 'bg-green-100 text-green-700'
              : 'bg-red-100 text-red-700'}">
              ${data.data.change > 0 ? '↑' : '↓'} ${Math.abs(data.data.change)}位
            </div>
          ` : ''}
          ${data.data.artwork ?
            `<img src="${data.data.artwork}" class="w-32 h-32 object-cover mt-3 rounded-xl border-2 border-purple-200 shadow-md">` : ''
          }
        `
      }
    },
    grid: {
      top: 50,
      right: 20,
      bottom: 20,
      left: 20,
      containLabel: true
    },
    animation: window.innerWidth > 768, // 仅PC端开启动画
    xAxis: {
      type: 'category',
      data: props.data.map(d => d.name),
      axisLabel: {
        interval: window.innerWidth < 768 ? 1 : 0, // 移动端间隔显示标签
        rotate: window.innerWidth < 768 ? 45 : 30,
        fontWeight: 'bold',
        color: '#3A0CA3'
      },
      axisLine: {
        lineStyle: {
          color: '#4CC9F0'
        }
      },
      axisTick: {
        show: false
      }
    },
    yAxis: {
      type: 'value',
      name: '影响力指数',
      nameGap: 30,  // 调整名称位置
      // nameLocation: 'center',  // 名称显示位置（start/center/end）
      nameTextStyle: {
        color: '#7209b7',
        fontWeight: 'bold'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(58, 12, 163, 0.1)'
        }
      },
      axisLabel: {
        color: '#4361ee',
        fontWeight: 'bold',
        fontSize: window.innerWidth < 768 ? 10 : 12
      }
    },
    series: [{
      data: props.data.map((d, i) => ({
        value: d.value,
        name: d.name,
        artwork: d.artwork,
        change: d.change,
        itemStyle: {
          color: generateGradient(i),
          shadowColor: i < 3 ? 'rgba(247, 37, 133, 0.5)' : 'rgba(58, 12, 163, 0.3)',
          shadowBlur: 10
        }
      })),
      type: 'bar',
      barWidth: '40%',
      label: {
        show: true,
        position: 'top',
        formatter: (params: any) => {
          const icons = ['🥇', '🥈', '🥉', '🎨']
          // return `${params.dataIndex < 3 ? icons[params.dataIndex] : icons[3]} ${params.value}`
          const icon = icons[params.dataIndex < 3 ? params.dataIndex : 3];
          const isMobile = window.innerWidth < 768;

          // PC 端横向排列，移动端纵向排列
          return isMobile
            ? `${icon}\n${params.value}`  // 移动端换行
            : `${icon}${params.value}`;   // PC 端横向
        },
        color: '#2b2d42',
        fontWeight: 'bold'
      },
      showBackground: true,
      backgroundStyle: {
        color: 'rgba(248, 249, 250, 0.6)',
        borderColor: '#e9ecef',
        borderWidth: 1,
        borderType: 'dashed'
      },
      emphasis: {
        itemStyle: {
          shadowColor: 'rgba(0, 0, 0, 0.8)',
          shadowBlur: 15
        }
      },
      // 添加三维效果
      roundCap: true,
      barGap: '30%',
      barCategoryGap: '40%',
      // 动画配置
      animation: true,
      animationDuration: 1500,
      animationEasing: 'elasticOut',
      animationDelay: (idx: number) => idx * 100
    }]
  }

  chart.setOption(options)

  // 添加悬停效果
  chart.on('mouseover', (params: any) => {
    chart.dispatchAction({
      type: 'highlight',
      seriesIndex: 0,
      dataIndex: params.dataIndex
    })
  })

  chart.on('mouseout', () => {
    chart.dispatchAction({ type: 'downplay' })
  })
}
</script>

<style scoped>
/* 悬停放大效果 */
.bg-gradient-to-br:hover {
  transform: translateY(-5px);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  box-shadow: 0 25px 50px -12px rgba(58, 12, 163, 0.25);
}

/* 奖牌颜色动画 */
@keyframes medal-glow {
  0% {
    text-shadow: 0 0 5px rgba(255, 209, 102, 0.8);
  }

  50% {
    text-shadow: 0 0 20px rgba(255, 209, 102, 1);
  }

  100% {
    text-shadow: 0 0 5px rgba(255, 209, 102, 0.8);
  }
}

.text-yellow-400 {
  animation: medal-glow 2s infinite;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .text-3xl {
    font-size: 1.5rem;
  }

  .h-96 {
    height: 300px;
  }

}

/* 移动端专属样式 */
@media (max-width: 640px) {
  .ranking-card {
    padding: 12px;
  }

  .chart-tooltip {
    max-width: 200px !important;
    font-size: 12px !important;
  }

  .user-rank {
    flex-direction: column;
    align-items: flex-start;
  }
}

/* 触摸反馈 */
@media (hover: none) {
  .interactive-element:active {
    transform: scale(0.98);
  }
}
</style>